package com.mock.ems.controller;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;
import com.mock.ems.service.ResourceService;
import com.mock.ems.service.ResourceServiceImpl;

import java.util.*;

/**
 * Created by lichengming on 2017/6/14.
 */
public class AdminController extends Controller {

    ResourceService resourceService = new ResourceServiceImpl();
    public void index() {
        renderJsp("/page/admin/admin_list.jsp");
    }

    public void pagination() {


        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        String selectSQL = "select * ";

        StringBuilder exceptSelectSQL = new StringBuilder(" from ems_admin where 1 = 1");

        List<Object> params = new ArrayList<Object>();

        String realName = getPara("real_name", "");
        if (StringUtil.isNotEmpty(realName.trim())) {
            exceptSelectSQL.append(" and real_name like ?");
            params.add("%" + realName.trim() + "%");
        }

        String login_account = getPara("login_account");
        if (StringUtil.isNotEmpty(login_account)) {
            exceptSelectSQL.append(" and login_account like ?");
            params.add('%' + login_account.trim() + "%");
        }

        exceptSelectSQL.append(" order by id desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString(),params.toArray());
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();

        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void edit() {

        Long id = getParaToLong("id");
        if (null != id) {
            Record adminRecord = Db.findById("ems_admin",id);
            if (null != adminRecord) {
                setAttr("record",adminRecord);
            }
        }

        Record admin = getSessionAttr("admin");
        //查找菜单
        List<Map<String,Object>> resourceList =
                resourceService.getMenuListByUserId(admin.getLong("id"));
        if (CollectionUtil.isNotEmpty(resourceList)) {
            setAttr("menuList", JSON.toJSONString(resourceList));
        }

        //查找编辑人的菜单
        List<Long> editUserMenuIdList = Db.query("select menu_id from ems_admin_menu where admin_id = ? ",id);
        if (CollectionUtil.isNotEmpty(editUserMenuIdList)) {
           setAttr("menuIdList",JSON.toJSONString(editUserMenuIdList));
        }
        renderJsp("/page/admin/admin_add.jsp");
    }

    @Before(Tx.class)
    public void save() {

        Long id = getParaToLong("id");
        Record record = null;
        if (id == null) {
            if (isLoginAccountExist(getPara("login_account"))) {
                renderJson(new JsonResult().status("-3").show("账号已经存在"));
                return;
            }
            record = new Record();
            record.set("create_time",new Date());
            record.set("status",1);
        }else {
            record = Db.findById("ems_admin",id);
        }

        if (null == record) {
            renderJson(new JsonResult().status("-1").show("保存失败"));
            return;
        }

        record.set("login_account",getPara("login_account"))
                .set("password",getPara("password"))
                .set("phone",getPara("phone"))
                .set("real_name",getPara("real_name"));

        if (null == id) {
            if (!Db.save("ems_admin",record)) {
                renderJson(new JsonResult().status("-2").show("保存失败"));
                return;
            }
        }else {
            if (!Db.update("ems_admin",record)) {
                renderJson(new JsonResult().status("-2").show("保存失败"));
                return;
            }
        }

        String menuIdList = getPara("menuIdList");
        if (StringUtil.isNotEmpty(menuIdList)) {
            String [] menuIdArray = menuIdList.split(",");
            if (menuIdArray.length > 0) {
                //删除掉原来的菜单
                Db.update("delete from ems_admin_menu where admin_id = ? ",id);
                for (String menuId : menuIdArray) {
                    Record menu_record = new Record();

                    menu_record.set("admin_id",record.getLong("id"))
                            .set("menu_id",menuId)
                            .set("create_time",new Date());
                    if (!Db.save("ems_admin_menu",menu_record)) {
                        throw new RuntimeException("save ems_admin_menu error");
                    }
                }
            }
        }
        renderJson(new JsonResult().status("000").show("保存成功"));

    }

    private boolean isLoginAccountExist(String loginAccount) {
        String sql = "select id from ems_admin where login_account = ? ";
        return Db.findFirst(sql,loginAccount) != null;
    }

    public void isAccountExist() {
        Long id = getParaToLong("id");
        if (null != id) {
            renderJson(true);
            return;
        }
        String sql = "select id from ems_admin where login_account = ? ";
        String loginAccount = getPara("login_account");
        Record record = Db.findFirst(sql,loginAccount);
        renderJson(record == null ? true:false);
    }

    @Before(Tx.class)
    public void delete() {

        String adminIdList = getPara("adminIdList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(adminIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from ems_admin where id in (");
        Object [] tips = new Object[adminIdList.split(",").length];
        int index = 0;
        for (String id : adminIdList.split(",")) {
            deleteSQL.append("?,");
            tips[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");
        boolean deleteResult = Db.update(deleteSQL.toString(),tips) == tips.length;

        
        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

}
